package model;

import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import entity.Tag;

public class TagModel extends BasicDAO<Tag, ObjectId> {
	
	private int pageSize = 100;
	public TagModel() {
		super(DBConnection.getMongo(), DBConnection.getMorphia(), DBConnection
				.getDatabase());
//		ds.ensureIndexes();
	}

	public List<Tag> getByCount(int total) {
		Query<Tag> q = ds.createQuery(Tag.class);
		return q.limit(total).asList();
	}

	public List<Tag> all(int currentPage) {
		Query<Tag> q = ds.createQuery(Tag.class);
		return q.limit(pageSize).offset(currentPage * pageSize).asList();
	}

	public Tag find(String alias) {
		Query<Tag> q = ds.find(Tag.class);
		q.field("alias").equal(alias);
		return q.get();
	}

	public Tag random() {
		long min = 1;
		long max = 200;
		long random = min + (int) (Math.random() * (max - min));
		Tag obj = new Tag();
		while (true) {
			Query<Tag> q = ds.createQuery(Tag.class);
			Tag tag = q.limit(-1).offset((int) random).get();
			if (tag.getAlias()!=null) {
				return tag;
			}
			else{
				break;				
			}
		}
		return obj;
	}

	public static void main(String[] args) {
		System.out.println("Start");
		TagModel model = new TagModel();
		Tag tag = model.random();
		System.out.println(tag.getAlias());
		System.out.println("Finish");
	}
}
